#include "rolebean.h"
#include "setting.h"

RoleBean::RoleBean()
{

}



RoleBean::RoleBean(QString account, QString password, int roleIndex)
{
    this->account = account;
    this->password = password;
    this->roleIndex = roleIndex;
}

RoleBean::~RoleBean()
{
}


QList<RoleBean> RoleBean::jsonToArray(QByteArray jsonArrayStr)
{
    QJsonParseError jsonError;
    QList<RoleBean> roleBeans;
    const QJsonDocument &document = QJsonDocument::fromJson(jsonArrayStr, &jsonError);
    if(document.isNull() || jsonError.error != QJsonParseError::NoError) return roleBeans;
    QJsonArray jsonArray = document.array(); //文档转化为Json对象
    for(int i = 0 ; i < jsonArray.size() ; i++){
        QJsonObject obj = jsonArray.at(i).toObject();
        QString account = obj.value("account").toString();
        QString password = obj.value("password").toString();
        int roleIndex = obj.value("roleIndex").toInt();
        roleBeans.append(RoleBean(account,password, roleIndex));
    }
    return roleBeans;
}

void RoleBean::createObject(QJsonObject &obj, RoleBean role)
{
    obj.insert("account", role.account);
    obj.insert("password", role.password);
    obj.insert("roleIndex", role.roleIndex);
}

QByteArray RoleBean::ArraytoJson(QList<RoleBean*> *roleBeans)
{
    QJsonDocument doc;
    QJsonArray array;
    if(roleBeans->isEmpty()) return "";
    for(int i = 0; i< roleBeans->size(); i++){
        QJsonObject obj;
        RoleBean *roleBean = roleBeans->at(i);
        createObject(obj, *roleBean);
        array.append(obj);
    }
    doc.setArray(array);
    return doc.toJson();
}


